package com.xing.ucenter.controller;


import com.google.gson.Gson;
import com.xing.servicebase.exceptionhandler.GuliException;
import com.xing.ucenter.entity.Member;
import com.xing.ucenter.entity.RefreshToken;
import com.xing.ucenter.service.MemberService;
import com.xing.ucenter.utils.ConstantPropertiesUtil;
import com.xing.ucenter.utils.HttpClientUtils;
import com.xing.ucenter.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@CrossOrigin
@Controller //注意这里不要设置@RestController 不用返回json数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;

    @Autowired
    private MemberService ucenterMemberService;

    /**
     * 1.生成微信二维码
     *
     * @param session
     * @return
     */
    @GetMapping("login")
    public String genQrConnect(HttpSession session) {

        //微信开放平台授权的baseUrl
        //? %s相当于占位符，可以填充参数
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //授权码需要传入加密过后的URL,必须使用
        //获取业务服务器的重定向地址
        String redirectUrl = constantPropertiesUtil.getRedirectUrl();

        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
            //url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置%s的参数值
        String url = String.format(
                baseUrl,
                constantPropertiesUtil.getAppId(),
                redirectUrl,
                "xingfuhao");
        //请求微信地址，重定向的方式
        return "redirect:" + url;
    }

    //2.获取扫描人的信息,我扫描后，就回调到这个地址接口，第三方应用
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
        System.out.println("code:" + code);
        System.out.println("state:" + state);
        System.out.println("session:" + session);

        try {
            //1.扫码之后获取code
            //2.根据code获取token

            //1.得到授权临时票据，授权码code 去请求token
            //2.拿着授权code请求，微信的固定地址，得到两个值，access_Token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    constantPropertiesUtil.getAppId(),
                    constantPropertiesUtil.getAppSecret(),
                    code);
            //请求这个拼接好的地址，得到返回的两个值access_token和openid
            //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //抛出的异常，由上一级或者调用者来捕获

            //使用gson转化工具Gson ，new对象 Gson的值
            Gson gson = new Gson();

            //把token转化为Map形式的键值对
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String refresh_token = (String) mapAccessToken.get("refresh_token");

            String openid = (String) mapAccessToken.get("openid");

            //判断该微信信息是否注册过
            Member member = ucenterMemberService.getMemberByOpenid(openid);
            if (member == null) {

                //获取用户个人信息
                //3.拿着access_token和openid,再去请求微信提供的固定地址，获取扫描人的信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //再次拼接微信地址
                String userInfoUrl = String.format(baseUserInfoUrl,
                        access_token,
                        openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);

                //获取微信个人信息json信息进行转换
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                // String province = (String) userInfoMap.get("province");
                //String privilege = (String) userInfoMap.get("privilege");

                System.out.println("nickname:" + nickname);
                System.out.println("headimgurl:" + headimgurl);
                // System.out.println("privilege:" + privilege);
                //System.out.println("province:" + province);

                //把微信信息注册到数据库的表里面
                //微信返回很多参数，我们只取几个重要的，来存到我们的数据库表里面。
                member = new Member();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                member.setGmtCreate(new Date());
                member.setGmtModified(new Date());
                ucenterMemberService.save(member);
            }

            //使用jwt生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //返回首页面
//            return "redirect:http://localhost:8160/api/ucenter/wx/refreshtoken?token=" + jwtToken;
            return "redirect:http://localhost:8160/api/ucenter/wx1/refreshtoken?refresh_token=" + refresh_token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "登录失败");
        }
    }

    @GetMapping("3000")
    public String getToken() {
        return "来到了谷粒学院的前端页面并且带着token来的";
    }

    //刷新token
    @GetMapping("refreshtoken")
    public RefreshToken getRefreshtoken(String refresh_token){
        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
                    + constantPropertiesUtil.getAppId() + "&grant_type=refresh_token" +
                    "&refresh_token=" +refresh_token;
            String accessTokenInfo = HttpClientUtils.get(baseAccessTokenUrl);
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            Double expires_in = (Double) mapAccessToken.get("expires_in");
            String refreshtoken1 = (String) mapAccessToken.get("refresh_token");
            String openid = (String) mapAccessToken.get("openid");
            String scope = (String) mapAccessToken.get("scope");

            RefreshToken refreshToken = new RefreshToken();
            refreshToken.setAccessToken(access_token);
            refreshToken.setExpiresIn(expires_in);
            refreshToken.setRefreshToken(refreshtoken1);
            refreshToken.setOpenid(openid);
            refreshToken.setScope(scope);

            System.out.println(refreshToken);
            return refreshToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"刷新失败");
        }
    }

}
